package org.dtrevien.ihm;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.JPanel;

public class ImagePanel extends JPanel{

    private BufferedImage image, orig;
    private final int l = 20;
    private final Dimension imgSize;
    private float factor;
    private int x,y;
    
    public ImagePanel() {
       this.imgSize = new Dimension();
       this.factor = 1;
    }
    
    public void setFactor(float f) {
    	this.factor = f;
    }
    
    public void setImage(BufferedImage img) throws IOException {
    	this.orig = img;
    	this.image = getScaledImage(img);
    	this.imgSize.setSize(this.image.getWidth(), this.image.getHeight());
    }
    
    public void redraw() throws IOException {
    	this.image = getScaledImage(this.orig);
    	this.imgSize.setSize(this.image.getWidth(), this.image.getHeight());
    	this.repaint();
    }
    
    public BufferedImage getScaledImage(BufferedImage image) throws IOException {
        int imageWidth  = image.getWidth();
        int imageHeight = image.getHeight();
        int width = (int) (imageWidth*this.factor);
        int height = (int) (imageHeight*this.factor);

        AffineTransform scaleTransform = AffineTransform.getScaleInstance(this.factor, this.factor);
        AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);

        return bilinearScaleOp.filter(
            image,
            new BufferedImage(width, height, image.getType()));
    }


    @Override
    public void paintComponent(Graphics g) {
    	g.clearRect(0, 0, this.getWidth(), this.getHeight());
    	if (this.image != null){
    		g.setColor(Color.GRAY);
    		g.fillRect(0, 0, this.getWidth(), this.getHeight());
    		/*float alpha = 0.5f;
    		for (int i = 0; i < this.l; i++) {
    			alpha-=0.5f/this.l;
    			g.setColor(new Color(0, 0, 0, alpha/1.5f));
        		g.drawRect(this.getWidth()/2-(this.imgSize.width+i)/2,
        				this.getHeight()/2-(this.imgSize.height+i)/2,
        				this.imgSize.width+i,
        				this.imgSize.height+i);
			}*/
    		g.drawImage(this.image, this.x+(this.getWidth()/2-this.imgSize.width/2),
    				this.y+(this.getHeight()/2-this.imgSize.height/2), null);
    	}
    			 

    }

	public float getFactor() {
		return this.factor;
	}

	public void setImagePosition(int i, int j) {
		this.x = i;
		this.y = j;
		repaint();
	}

}
